#!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
简单的快乐8历史数据排序修复脚本
"""
import csv
import os
from datetime import datetime

def fix_kl8_data_order():
    """修复快乐8历史数据的排序"""
    # 文件路径
    file_path = os.path.join(os.path.dirname(__file__), 'kl8_history.csv')
    
    # 检查文件是否存在
    if not os.path.exists(file_path):
        print(f"文件不存在: {file_path}")
        return False
    
    try:
        # 读取CSV文件
        print("正在读取快乐8历史数据...")
        data = []
        with open(file_path, 'r', encoding='utf-8') as f:
            reader = csv.reader(f)
            header = next(reader)  # 读取表头
            for row in reader:
                if len(row) >= 22:  # 确保行数据完整
                    data.append(row)
        
        print(f"原始数据行数: {len(data)}")
        
        # 按日期排序（从旧到新）
        # 日期在索引1位置
        data.sort(key=lambda x: x[1])
        
        print(f"排序后数据行数: {len(data)}")
        
        # 保存回文件
        backup_path = file_path + '.backup'
        print(f"正在创建备份文件: {backup_path}")
        os.rename(file_path, backup_path)
        
        print("正在保存排序后的数据...")
        with open(file_path, 'w', newline='', encoding='utf-8') as f:
            writer = csv.writer(f)
            writer.writerow(header)  # 写入表头
            writer.writerows(data)   # 写入数据
            
        print("数据排序修复完成!")
        return True
        
    except Exception as e:
        print(f"修复数据排序时发生错误: {e}")
        return False

if __name__ == "__main__":
    fix_kl8_data_order()